<script lang="ts" setup>
interface TransferTaskStatusResp {
  tasks: TransferTaskStatus[];
}

interface TransferTaskStatus {
  filename: string;
  src: string;
  dst: string;
  progress: number;
  size: number;
  transferredSize: number;
  transferSpeed: number;
  netBandwidth: number;
}

const fetchTaskStatus = async () => {
  const data = await $fetch<TransferTaskStatusResp>(
    "http://49.232.250.113:8080/tasks"
  );

  taskStatus.value = data.tasks.map((task) => {
    task.progress = (task.transferredSize / task.size) * 100;
    return task;
  }) as TransferTaskStatus[];
  taskStatus.value.reverse();
};

const cleanTaskStatus = async () => {
  await $fetch("http://49.232.250.113:8080/tasks/clean");
};

onMounted(() => {
  intervalId = setInterval(fetchTaskStatus, 1000);
});

onUnmounted(() => {
  clearInterval(intervalId);
});

let intervalId: NodeJS.Timeout;
const taskStatus = ref([] as TransferTaskStatus[]);
fetchTaskStatus();
</script>

<template>
  <div>
    <v-container width="66%">
      <v-row class="justify-space-between mt-6">
        <div class="text-h6">文件传输任务：</div>
        <v-btn
          class="float-right"
          text="清除列表"
          rounded
          @click="cleanTaskStatus"
        />
      </v-row>
      <v-row v-for="(task, index) in taskStatus" :key="index" class="mt-6">
        <v-card rounded class="w-full">
          <v-card-title>{{ task.filename }}</v-card-title>
          <v-card-text>
            <div>源目录： {{ task.src }}</div>
            <div>目标目录： {{ task.dst }}</div>

            <div class="mt-4">
              <span>
                传输速率 / 网络带宽:
                {{ transformSize2HumanReadable(task.transferSpeed) }}/s /
                {{ transformSize2HumanReadable(task.netBandwidth) }}/s
              </span>
              <span class="float-right">
                已传输大小 / 文件大小:
                {{ transformSize2HumanReadable(task.transferredSize) }}
                /
                {{ transformSize2HumanReadable(task.size) }}
              </span>
            </div>
            <v-progress-linear
              v-model="task.progress"
              clickable
              color="primary"
              class="mt-4"
            />
          </v-card-text>
        </v-card>
      </v-row>
    </v-container>
  </div>
</template>
